package com.easykoo.web.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.Iterator;

public class CollectionTag extends TagSupport {
    private String var;

    private Iterator iterator;

    public int doStartTag() throws JspException {
        FormTag formTag = (FormTag) getParent();
        PageInfo pageInfo = formTag.getPageInfo();
        if (pageInfo != null && pageInfo.getResult() != null && pageInfo.getResult().size() != 0) {
            iterator = pageInfo.getResult().iterator();
            if (iterator != null && iterator.hasNext()) {
                pageContext.getSession().setAttribute(var, iterator.next());
                return EVAL_BODY_INCLUDE;
            } else {
                return SKIP_BODY;
            }
        }
        return SKIP_BODY;
    }

    @Override
    public int doAfterBody() throws JspException {
        if (iterator != null && iterator.hasNext()) {
            pageContext.setAttribute(var, iterator.next());
            return EVAL_BODY_AGAIN;
        }
        return SKIP_BODY;
    }

    public String getVar() {
        return var;
    }

    public void setVar(String var) {
        this.var = var;
    }

}